<?php

namespace app\common\controller;

use think\Controller;
use think\Request;
use think\Exception;
use think\Config;
use app\common\traits\controller\TraitController;
use Lcobucci\JWT\Builder;
use Lcobucci\JWT\ValidationData;
use Lcobucci\JWT\Parser;
use think\Loader;
use EasyWeChat\Foundation\Application;
use EasyWeChat\MiniProgram\Encryption\Encryptor;
use \think\Session;
use think\helper\Str;

abstract class Apps extends Controller
{
    use TraitController;

    protected $token            = false;
    public static $api_user     = null;

    protected $options = [
        'debug'   => false,
        'app_id'  => 'wx5a1090e16a2f3e95',// AppID
        'secret'  => '7d7f576e91c8e8dc1af4fbeb6938ac2a',// AppSecret
        'token'   => 'i9ch3f2ca',// Token
        'aes_key' => 'RBuTcKRnHXbrLr4mrjQJW16ezM0UlggeHJZfu09ecnf',// 
        'oauth' => [
            'scopes'   => ['snsapi_base'],
            'callback' => '/user/callback',
        ],
        /**
         * 微信支付
         */
        'payment' => [
            'merchant_id'        => '1419891902',
            'key'                => '845d5f1153c27beed29f479640445148',
            'cert_path'          => 'path/to/your/cert.pem', // XXX: 绝对路径！！！！
            'key_path'           => 'path/to/your/key',// XXX: 绝对路径！！！！
        ],
        /**
         * Guzzle 全局设置
         *
         * 更多请参考： http://docs.guzzlephp.org/en/latest/request-options.html
         */
        'guzzle' => [
            'timeout' => 3.0, // 超时时间（秒）
            'verify'  => false, // 关掉 SSL 认证（强烈不建议！！！）
        ],
        /**
         * 小程序
         */
        'mini_program' => [
            'token'   => '',
            'aes_key' => '',
            'app_id'  => 'wx3bdfa8264cbf60e5',// AppID
            'secret'  => 'e7e23067297b7ba54b5667001ab2a624',// AppSecret
        ]
    ];

    protected function checkRight()
    {
        if ($token = $this->request->header('token') ? : $this->request->param('token')) {
            $data = new ValidationData();
            $data->setIssuer('http://shsytour.cn');
            $data->setAudience('http://shsytour.cn');
            $data->setId(Config::get('key'));
            //$data->setCurrentTime(time() + 3000);
            
            try {
                $token = (new Parser())->parse((string) $token);
                if ($token->validate($data)) {
                    $this->token = $token;
                }else{
                    throw new Exception('check token fail3', '800');
                }
            } catch (\Exception $e) {
                throw new Exception('check token fail2', '800');
            }
        }else{
            throw new Exception('check token fail1', '800');
        }
    }

    protected function tokenUserInfo()
    {
        try {
            $this->checkRight();
            $token = (new Parser())->parse((string) $this->token);
            $user  = json_decode($token->getClaim('user_info'));

            if (!$user) {
                throw new Exception('Member information does not exist', 800);
            }
            self::$api_user = Loader::model('Users')->getUserInfo(['id' => $user]);
        } catch (\Exception $e) {
            throw $e;
        }  
    }

    public static function setToken($user)
    {
        $token = (new Builder())->issuedBy('http://shsytour.cn')
                                ->canOnlyBeUsedBy('http://shsytour.cn')
                                ->identifiedBy(Config::get('key'), true)
                                //->expiresAt(time() + 3600)
                                ->with('user_info', $user)
                                ->getToken();

        return $token->__toString();
    }

    public function wxsession()
    {
        $session = (new Application($this->options))->mini_program->sns->getSessionKey($this->request->get('code'));
        return (new Encryptor($session->session_key, $this->request->get('iv')))->decryptData($this->request->get('decryptData'));
    }

    public function getSendNotice()
    {
        $touser  = $this->request->get('touser');
        $form_id = $this->request->get('formId');

        $data = [
            'touser'      => $touser,
            'template_id' => 'p7FLbk3D4KdnLyGYzmF5VPKSLao5H74HyzJLqlPRRjs',
            'page'        => '',
            'form_id'     => $form_id,
            'data'        => [
                "keyword1" => [
                      "value" => "100000元", 
                      "color" => "#173177"
                ], 
                "keyword2" => [
                      "value" => "高兴!!!", 
                      "color" => "#173177"
                ]
            ],

            'emphasis_keyword' => 'keyword1.DATA',
        ];

        return (new Application($this->options))->mini_program->notice->send($data);
    }

    static public function uuid()
    {
        if (!function_exists('uuid_create')) {
            return \Ramsey\Uuid\Uuid::uuid4()->toString();
        }
        return uuid_create(); 
    }

    public function postRegister($info, $phone_code, $uuid)
    {
        $re = model('PhoneCode')->check($phone_code,$uuid);
        if (!$re) {
            return $this->error(model('PhoneCode')->getError());
        }
        //修改cheack
        // $accepted = input('post.accepted');
        // if (empty($accepted)) {
        //     return $this->error(lang('请同意双辉旅程网服务协议'),$url = null,'',$wait=3);
        // }
        
        //user入库
        return $user = Loader::model('Users')->addUser($info);
        
    }

    public function base64EncodeImage($image_file, $base_url = 'https://api.shsytour.cn/')
    {
        $image_file = Str::startsWith($image_file, ['/', '\\']) ? '.' . $image_file : $image_file;
        try {
            $image        = new \think\File($image_file);
            $image_data   = $image->openFile('r')->fread($image->getSize());
            $base64_image = 'data:' . $image->getMime() . ';base64,' . chunk_split(base64_encode($image_data));
            return $base64_image;
        } catch (\Exception $e) {
            return $base_url . $image_file;
        }
    }
    
}
